# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

import collections
import datetime
import json
import logging
import os
import sys
import pandas as pd
from matplotlib import pyplot as plt

class OeAnalyser(object):
  def __init__(self):
    self._ts = None
    self._submit_info = collections.defaultdict(list)
    self._fill_info = collections.defaultdict(list)
    self._symbols = set()

  @property
  def symbol_list(self):
    return list(self._symbols)

  def get_submit_df(self, symbol):
    assert symbol in self._submit_info
    df = pd.DataFrame(self._submit_info[symbol])
    return df

  def get_fill_df(self, symbol):
    assert symbol in self._fill_info
    df = pd.DataFrame(self._fill_info[symbol])
    return df

  def on_order_event(self, event):
    if event['type'] != 'ORDER_EVENT':
      return
    event = event['event']
    self._ts = int(event['event_time'])
    event_type = event['type']
    symbol = "%s:%s" % (event['exchange_type'], event['symbol'])
    self._symbols.add(symbol)
    if event_type == 'ORDER_SUBMITTED':
      self._submit_info[symbol].append({
          'ts': self._ts,
          'symbol': symbol,
          'order_price': event['order_price'],
          'order_qty': event['order_qty'],
      })
    elif event_type == 'ORDER_FILLED':
      self._fill_info[symbol].append({
          'ts': self._ts,
          'symbol': symbol,
          'fill_price': event['fill_price'],
          'fill_qty': event['fill_qty'],
      })
    else:
      pass


def main():
  oe_analyser = OeAnalyser()
  data = json.load(open(sys.argv[1]))
  for info in data:
    oe_analyser.on_order_event(info)

  for symbol in oe_analyser.symbol_list:
    submit_df = oe_analyser.get_submit_df(symbol)
    ts = pd.DatetimeIndex(submit_df.ts)

    fill_df = oe_analyser.get_fill_df(symbol)
    ts = pd.DatetimeIndex(fill_df.ts)
    print("xxxxx: ", symbol, fill_df.fill_qty.sum() / submit_df.order_qty.sum())

if __name__ == '__main__':
  logging.basicConfig(level='DEBUG', format='%(levelname)8s %(asctime)s %(name)s] %(message)s')
  main()
